package player.ui.browse;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.Rectangle;

public class AutoSizeLayout implements LayoutManager{
	int gapY=1;
	int gapX=1;
	int ga=100;
	float rate=1.333f;
	int maxImgWidth=150;
	
	public void addLayoutComponent(String name, Component comp) {
		
	}

	public void layoutContainer(Container cn) {
		
		int count = cn.getComponentCount();
		
		int maxClumbCount=20;
		int rowCount=1;
		int clumbCount=1;
		int count2=0;
		float iW=0;
		float iH=0;
		
		gapX=cn.getWidth()/ga;
		gapY=cn.getHeight()/ga;
		
		for(clumbCount=1;clumbCount<maxClumbCount;clumbCount++){
			iW=(cn.getWidth()-gapX*clumbCount)/clumbCount;
			iH=iW/rate;
			rowCount=(int) (cn.getHeight()/(iH+gapY));
			count2=clumbCount*rowCount;
			if(count2>=count){
				break;
			}
		}
		
		if(iW>maxImgWidth){
			iW=maxImgWidth;
			iH=maxImgWidth/rate;
		}
	    
	    int xOffset=gapX/2;
	    int yOffset=gapY/2;
	    
	    for (int i = 0 ; i < count ; i++) {
	    	Component m = cn.getComponent(i);
	    	if(m.getName()!=null){
	    		if(m.getName().equals("glassPanel")){
		    		System.out.println("EEEEEEEEEERR "+m);
		    	}
	    	}
	    	
	    	Rectangle rec=new Rectangle();
	    	rec.x=xOffset;
	    	rec.y=yOffset;
	    	rec.width=(int) iW;
	    	rec.height=(int) iH;

	    	boolean isEnd=false;
	    	if((xOffset+2*iW)>cn.getWidth()){
	    		isEnd=true;
	    	}
	    	if(isEnd){
	    		xOffset=gapX/2;
	    		yOffset+=(iH+gapY);
	    	}else{
	    		xOffset+=(iW+gapX);
	    	}
	    	m.setBounds(rec);
	    }
	    
	}
	
	boolean rowCountAvail(Container cn,int count,int rowCount,float rate){
		boolean b=false;
		float iH=cn.getHeight()/rowCount;
		float iW=iH*rate;
		
		float iWH=iH*iW;
		
		int cWH=cn.getWidth()*cn.getHeight();
		int count2=(int) (cWH/iWH);
		if(count2>=count){
			b=true;
		}
		return b;
	}

	public Dimension minimumLayoutSize(Container parent) {
		return new Dimension(0,0);
	}

	public Dimension preferredLayoutSize(Container parent) {
		return new Dimension(0,0);
	}

	public void removeLayoutComponent(Component comp) {
		
	}
	
}
